<template>
  <q-dialog v-model="visible">
    <q-card style="max-width: 95vw; max-height: calc(100vh - 2rem); overflow-x: hidden">
      <modify-storage-posture ref="modifyStoragePosture" modify @remove="removePosture"/>
      <modify-storage-posture ref="newStoragePosture" @remove="removePosture"/>
      <q-card-section class="flex items-center q-gutter-x-sm">
        <div class="text-h6">{{ (state ? '新增' : '修改') + '库位规格' }}</div>
        <photo-dialog v-if="mode==='device'" label="查看当前相机" color="primary"/>
        <q-space/>
        <template v-if="!state">
          <q-btn color="negative" icon="delete" @click="remove" label="删除当前库"/>
        </template>
      </q-card-section>
      <q-separator/>
      <q-stepper
        v-model="step"
        vertical header-nav
        color="primary"
        animated
      >
        <!--  设置规格   -->
        <q-step
          :name="1"
          title="库位规格"
          caption="设置库位的排、列、层和场景与分组等规格信息"
          icon="settings"
          :done="step > 1"
        >
          <div class="q-gutter-y-sm" style="max-width: 25rem">
            <q-input dense outlined v-model="norm.name" label="名称"/>
            <div class="row q-gutter-x-sm">
              <q-input class="col" dense outlined v-model="norm.length" type="number" label="长"/>
              <q-input class="col" dense outlined v-model="norm.width" type="number" label="宽"/>
              <q-input class="col" dense outlined v-model="norm.height" type="number" label="高"/>
            </div>
            <q-select
              :use-input="!norm.scenario"
              outlined behavior="menu"
              v-model="norm.scenario"
              :options="scenarios" @new-value="newScenario"
              label="选择或新增场景" clearable
            />
            <q-select
              v-if="norm.scenario"
              :use-input="!norm.group"
              outlined behavior="menu"
              v-model="norm.group"
              :options="groups" @new-value="newGroup"
              label="选择或新增库位组" clearable
            />
            <q-slide-transition>
              <div class="full-width"
                v-if="norm.name && norm.length > 0 && norm.width > 0 && norm.height > 0 && norm.scenario && norm.group">
                <q-btn
                  v-if="norm.name && norm.length > 0 && norm.width > 0 && norm.height > 0 && norm.scenario && norm.group"
                  class="full-width" @click="step = 2" color="primary" label="确认规格信息" icon="check"/>
              </div>
            </q-slide-transition>
          </div>
        </q-step>
        <!--  设置姿态     -->
        <q-step
          :name="2"
          title="库位姿态点"
          caption="设置准备点，抓取点，拍照点"
          icon="create_new_folder"
          :header-nav="false"
          :done="step > 2"
        >
          <div class="q-gutter-y-sm">
            <div class="row q-gutter-x-sm">
              <q-btn
                rounded
                v-for="(item,index) in typeList"
                :key="index"
                color="primary"
                text-color="white"
                :icon="iconOptions[item.type]"
                :label="item.name"
                :title="item.name"
                @remove="onResetClick(index,item.type)"
                @click="modifyStoragePosture.show(item)"
              />
              <q-space/>
              <q-btn v-if="typeList.length === 0" rounded outline color="primary" label="新增准备姿态" icon="home" @click="addMainPosture('home')"/>
              <q-btn-dropdown v-else outline color="primary" label="新增姿态" icon="add">
                <q-item clickable v-close-popup @click="addMainPosture('calibration')">
                  <q-item-section side>
                    <q-icon name="add_a_photo" size="1.5rem"/>
                  </q-item-section>
                  <q-item-section>
                    <q-item-label>校准姿态</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup @click="addMainPosture('normal')">
                  <q-item-section side>
                    <q-icon name="share" size="1.5rem"/>
                  </q-item-section>
                  <q-item-section>
                    <q-item-label>过渡姿态</q-item-label>
                  </q-item-section>
                </q-item>
              </q-btn-dropdown>
            </div>
            <q-separator/>
            <div class="row">
              <template v-for="index of norm.length*norm.width" :key="index">
                <q-btn v-if="occupied.includes(index)" color="secondary" :label="index" class="text-bold"
                       :style="'width: calc(100%/'+norm.width+');height: calc(100%/'+norm.length+')'"
                       @click="modifyPosture(index)"/>
                <q-btn v-else :label="index"
                       :color="occupied.includes(index)?'secondary':'standard'"
                       :outline="!occupied.includes(index)"
                       class="text-weight-bolder"
                       :style="'width: calc(100%/'+norm.width+');height: calc(100%/'+norm.length+')'"
                       @click="addPosture(index)"
                />
              </template>
            </div>
            <q-btn v-if="state" label="创建库位" color="primary" icon="add" class="full-width" @click="newStorage"/>
            <div v-else class="text-right q-gutter-x-sm">
              <q-btn label="保存库位修改" color="primary" icon="save" @click="modifyStorage"/>
              <q-btn label="还原姿态修改" color="secondary" icon="sync" @click="getPostureList"/>
            </div>
          </div>
        </q-step>
      </q-stepper>
    </q-card>
  </q-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { api } from 'boot/axios.js'
import { useAPIStore } from 'stores/api/index.js'
import { useQuasar } from 'quasar'
import { useFunctionsStore } from 'stores/functions/index.js'

import ModifyStoragePosture from 'components/transport/catch/storage/ModifyStoragePosture.vue'
import PhotoDialog from 'components/transport/catch/posture/PhotoDialog.vue'

// 姿态图标
const iconOptions = ref({
  calibration: 'add_a_photo',
  home: 'home',
  normal: 'share'
})

export default {
  name: 'SpecieFiction',
  components: {
    PhotoDialog,
    ModifyStoragePosture
  },
  setup (props, context) {
    const mode = computed(() => useFunctionsStore().mode)
    const $q = useQuasar()
    const modifyStoragePosture = ref()
    const newStoragePosture = ref()

    const visible = ref(false)
    // 判断是否是修改或添加
    const state = ref(true)
    // 创建规格得进度
    const step = ref(1)
    // 包含的坐标
    const occupied = ref([])

    const typeList = ref([]) // 拍照点和准备点list
    const referenceList = ref([]) // 参考点List
    const norm = ref({ // 库位规格
      name: '',
      height: 1,
      width: 1,
      length: 1
    })
    const groups = ref([])
    const scenarios = ref([])
    const scenario = computed(() => norm.value.scenario)
    watch(scenario, value => {
      if (value === '') return
      api.get(useAPIStore().postureUrl + 'storage/groups/' + value).then(rs => {
        groups.value = rs.data
      })
    })

    // 获取场景列表
    function getScenario () {
      api.get(useAPIStore().postureUrl + 'storage/scenarios').then(rs => {
        scenarios.value = rs.data
      })
    }

    // 获取数据库李的姿态点
    function getPostureList () {
      occupied.value = []
      typeList.value = []
      referenceList.value = []
      api.get(useAPIStore().postureUrl + 'posture/storage/' + norm.value.id).then(rs => {
        referenceList.value = rs.data.filter(item => item.type === 'reference')
        typeList.value = rs.data.filter(item => item.type !== 'reference')
        referenceList.value.forEach(item => {
          const nList = item.name.replace(norm.value.name, '').replace('-', '').split('_')
          occupied.value.push((nList[0] - 1) * norm.value.width + nList[1] * 1)
        })
        $q.notify({ message: '已加载姿态点数据', type: 'positive', position: 'bottom' })
      })
    }

    // 保存对于库位内姿态点的修改
    function addAllPosture (id) {
      const postureList = typeList.value.concat(referenceList.value)
      api.put(useAPIStore().postureUrl + 'posture/' + id, postureList).then(rs => {
        $q.notify({
          type: 'positive',
          message: state.value ? '库位新增成功' : '库位修改已保存',
          position: 'bottom'
        })
        context.emit('getBank')
        visible.value = false
      })
    }

    return {
      modifyStoragePosture,
      newStoragePosture,
      visible,
      mode,
      norm,
      groups,
      step,
      occupied,
      iconOptions,
      typeList,
      scenario,
      scenarios,
      state,
      getPostureList,
      show (data) {
        getScenario()
        // 判断是否是修改姿态
        if (data) {
          step.value = 2
          norm.value = data
          getPostureList()
          state.value = false
        } else {
          step.value = 1
          state.value = true
          // 清空姿态
          norm.value = {
            name: '',
            height: 1,
            width: 1,
            length: 1
          }
          occupied.value = []
          typeList.value = []
          referenceList.value = []
        }
        visible.value = true
      },
      newScenario (val, done) {
        if (!scenarios.value.includes(val)) {
          scenarios.value.push(val)
          done(val, 'add-unique')
        }
      },
      newGroup (val, done) {
        if (!groups.value.includes(val)) {
          groups.value.push(val)
          done(val, 'add-unique')
        }
      },
      newStorage () {
        $q.dialog({
          title: '规格配置已完成',
          message: '是否要保存库位规格？',
          cancel: '取消',
          ok: '确认'
        }).onOk(() => {
          api.post(useAPIStore().postureUrl + 'storage', norm.value).then(rs => {
            if (rs.data) {
              addAllPosture(rs.data.id)
            }
          })
        })
      },
      modifyStorage () {
        $q.dialog({
          title: '库位姿态修改',
          message: '是否要保存对库位的修改？',
          cancel: '取消',
          ok: '确认',
          persistent: true
        }).onOk(() => {
          api.put(useAPIStore().postureUrl + 'storage', norm.value).then(rs => {
            addAllPosture(norm.value.id)
          })
        })
      },
      modifyPosture (index) {
        referenceList.value.forEach((item, i) => {
          // 算出他的下标判断
          const nList = item.name.replace(norm.value.name, '').replace('-', '').split('_')
          // 等于点击的下标需要修改姿态坐标
          if ((nList[0] - 1) * norm.value.width + nList[1] * 1 === index) {
            modifyStoragePosture.value.show(referenceList.value[i])
          }
        })
      },
      addPosture (index) {
        // 计算出规格名字
        const a = Math.floor(index / norm.value.width)
        const b = index - a * norm.value.width
        let x, y
        if (b === 0) {
          x = a
          y = norm.value.width
        } else {
          x = a + 1
          y = b
        }
        $q.dialog({
          title: '设置端点' + index,
          message: '设置该位置为端点？',
          cancel: '取消',
          ok: '确认'
        }).onOk(() => {
          const endpoint = {}
          endpoint.name = norm.value.name + '-' + x + '_' + y + '_' + norm.value.height
          endpoint.id = norm.value.name + '-' + x + '_' + y + '_' + norm.value.height
          endpoint.type = 'reference'

          occupied.value.push(index)
          referenceList.value.push(endpoint)

          newStoragePosture.value.show(endpoint)
        })
      },
      removePosture (posture) {
        if (typeList.value.indexOf(posture) !== -1) {
          const index = typeList.value.indexOf(posture)
          typeList.value.splice(index, 1)
          $q.notify({
            message: '基准姿态点' + posture.name + '删除成功',
            type: 'positive',
            position: 'bottom'
          })
          return
        }
        if (referenceList.value.indexOf(posture) !== -1) {
          const index = referenceList.value.indexOf(posture)
          referenceList.value.splice(index, 1)
          occupied.value.splice(index, 1)
          $q.notify({
            message: '姿态点' + posture.name + '删除成功',
            type: 'positive',
            position: 'bottom'
          })
        }
      },
      addMainPosture (type) {
        const endpoint = {}
        endpoint.type = type
        typeList.value.push(endpoint)
        newStoragePosture.value.show(endpoint)
      },
      remove () {
        $q.dialog({
          title: '删除库位',
          message: '是否要删除该库位？',
          cancel: '取消',
          ok: '确认'
        }).onOk(() => {
          api.delete(useAPIStore().postureUrl + 'storage/' + norm.value.id).then(rs => {
            if (rs.data === 'deleted') {
              $q.notify({
                message: '删除库位成功',
                type: 'positive'
              })
              visible.value = false
              context.emit('getBank')
            } else {
              $q.notify({
                message: '删除库位失败',
                type: 'negative'
              })
            }
          })
        })
      }
    }
  }
}
</script>
